import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'

// 密钥对生成 http://web.chacuo.net/netrsakeypair

const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n' +
  'nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=='

const privateKey = 'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n' +
  '7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n' +
  'PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n' +
  'kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n' +
  'cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n' +
  'DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n' +
  'YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n' +
  'UP8iWi1Qw0Y='

// 加密
export function encrypt(txt: string): string {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

// 解密
export function decrypt(txt: string): string {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey) // 设置私钥
  return encryptor.decrypt(txt) // 对数据进行解密
}

// 将指定字符串转化为驼峰字符串
export function toCamelCase(str: string, delimiter: string): string {
  const regex = new RegExp(`\\${delimiter}(\\w)`, 'g');
  return str.replace(regex, (_, char) => char.toUpperCase());
}

// 与path.resolve一致
export function resolvedPath(...paths: string[]): string {
  const separator = '/';
  let resolvedPath = '';

  for (let i = 0; i < paths.length; i++) {
    const path = paths[i];

    if (!path) continue;

    if (resolvedPath.endsWith(separator)) {
      resolvedPath += path.startsWith(separator) ? path.slice(1) : path;
    } else {
      resolvedPath += path.startsWith(separator) ? path : separator + path;
    }
  }

  return resolvedPath;
}

// 将url中的${}替换成指定变量
export function replaceUrlVariables(url: string, variables: object): string {
  if (!variables) {
    return url
  }
  // 匹配 ${key} 格式的正则表达式
  const regex = /\${(.*?)}/g;
  
  // 使用 replace 方法，将匹配到的变量替换为对象中的对应值
  const replacedUrl = url.replace(regex, (match, key) => {
    // 从对象中获取对应的变量值
    const value = variables[key.trim()];
    return value !== undefined ? value : 'undefined';
  });

  return replacedUrl;
} 

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str: string): string {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

